#!/usr/bin/env node

const http = require('http'),
      fs   = require('fs'),
      qs   = require('querystring');

let items = [];

function genPage(){
  
  let html = fs.readFileSync('./template.html').toString('utf8');
    let dom = (items.length===0)?'':items.map(i=>'<li>'+i+'</li>').join('\n');
       
    html = html.replace('*',dom);

  return html;

}

http.createServer((req, res) =>{
  if(req.url !== '/'){
    res.statusCode = 404;
    res.setHeader('Content-type','text/html');
    res.end('<h1>Not Found!</h1>');
    return;
  }

  let data = '';
  req.on('data',chunck => data +=chunck);
  req.on('end',()=>{
    let item = qs.parse(data).item;
    if(item !== '' && typeof item !== 'undefined') items.push(item);

    res.writeHead(200,{
      'Content-type':'text/html',
      'Content-length':Buffer.byteLength(genPage())
    });
    res.end(genPage());    
  });


}).listen(8080);
